const { query } = require('express')
const express = require('express')
const router = express.Router()
const execSQL= require('../db/mysql')
const Token = require('../modules/token')

const formidable = require('formidable')
const fs = require('fs')
const path = require('path')

//注册路由
router.post('/register',(req, res) => {
    let {username, password} = req.body;
    const setsql = `insert into blogs(username, password, createtime) values ('${username}', '${password}', ${Date.now()});`;
    const getsql = `select * from blogs where username='${username}'`;    
    execSQL(getsql)
        .then((data) =>{
            if(data != ''){
                console.log('已有账号')
            }else{
               execSQL(setsql) 
               console.log('正在注册')
               res.send({
                   mes: '注册成功',
                   status: 200
               })
            }
        })
        .catch((err) =>{
            console.log('注册失败')
        })
})

//登录路由
router.post('/login', (req, res) => {
    let {username, password} = req.body;
    const sql = `select * from blogs where username='${username}'`;
    execSQL(sql)
        .then((data) => {
            if(data != ''){
                const ifpw = data.some((x)=>x.password == password)
                if(ifpw){
                    const tokenKey= Token.on(username);
                    res.send({mes: '密码正确',status: 200, tokenKey})
                } else{
                    res.send({mes: '密码错误',status: 200})
                } 
                return
            }
            res.send({mes: '未注册', status: 200})
            
        })
        .catch((err) =>{
            console.log(err)
        })

})

//主页
router.get('/home',(req, res) => {
    const sql = 'select * from blogpost';
    execSQL(sql)
    .then((data)=>{
        res.send({
            status: 200,
            data
        })
    })
    .catch((err)=>{
        console.log(err)
    })
})
//look
router.get('/look',(req, res)=>{
    const getid = req.query
    const sql = `select * from blogpost where id= '${getid.id}'`
    execSQL(sql)
    .then((data)=>{
        res.send({
            status: 200,
            data
        })
    })
    .catch((err)=>{
        console.log(err)
    })
})
//look/comment
router.get('/look/getComment',(req, res)=>{
    let {commenttitle}=req.query
    console.log(commenttitle)
    //获取评论，排序上层显示最新排序
    const sql = `select * from blogcomment where title='${commenttitle}' order by commenttime desc`
    console.log(sql)
    execSQL(sql)
    .then((data)=>{
        res.send({
            status: 200,
            data
        })
    })
    .catch((err)=>{
        console.log(err)
    })
})
//look/postComment
router.post('/look/postComment',(req, res)=>{
    let {username, commentdata, commenttime}=req.body
    const sql =`insert into blogcomment(username, commenttext, commenttime) values ('${username}', '${commentdata}', '${commenttime}')`
    console.log(sql)
    execSQL(sql)
    .then((data)=>{
        res.send({
            status: 200
        })
        console.log('评论成功')
    })
    .catch((err)=>{
        console.log('评论失败')
    })
})
// look/getReply评论回复
router.get('/look/getReply',(req, res)=>{
    let {username, commentreply}=req.query;
    const sql=`select * from blogcomment where username='${username}' and commentreply='${commentreply}'`
    execSQL(sql)
    .then((data)=>{
        res.send({
            mes: '回复获取成功',
            status: 200,
            data
        })
    })
    .catch((err)=>{
        console.log('回复获取出错')
    })
})
//look/delReply删除评论
router.get('/look/delReply',(req, res)=>{
    let {username, commenttime}=req.query;
    const sql =`delete from blogcomment where username='${username}' and commenttime='${commenttime}'`
    execSQL(sql)
    .then((data)=>{
        res.send({
            mes: true,
            status: 200,
        })
        console.log('删除语句执行成功')
    })
    .catch((err)=>{
        res.send({
            mes: false,
            status: 200,
        })
        console.log('删除语句执行失败')
    })
})
//classify分类查询
router.get('/classify',(req, res)=>{
    let {classify} = req.query;
    if(classify){
        let sql = `select * from blogpost where classify='${classify}';`
        classify=="全部"?sql = 'select * from blogpost':'';
        execSQL(sql)
        .then((data)=>{
            if(data != ''){
                res.send({
                    mes: true,
                    status: 200,
                    data
                })
                console.log('分类查询完毕')
            }else{
                res.send({
                    mes: false,
                    status: 200,
                })
                console.log('分类查询为空')
            }
        })
        .catch((err)=>{
            console.log('分类查询失败')
        })
    }else{
        console.log('无分类参数')
    }
})
//message上传留言
router.post('/postMessage',(req, res)=>{
    let {username, messagebox, createtime} =req.body.data
    const sql = `insert into  blogmessage (username, messagebox,createtime) values ('${username}', '${messagebox}','${createtime}');`
    console.log(sql)
    execSQL(sql)
    .then((data)=>{
        res.send({
            mes: true,
            status: 200
        })
        console.log('留言成功')
    })
    .catch((err)=>{
        res.send({
            mes: false,
            status: 200,
            err
        })
        console.log('留言上传失败')
    })
})
//弹幕
router.get('/getMessage',(req, res)=>{
    const sql='select * from  blogmessage  order by createtime desc'
    console.log(sql)
    execSQL(sql)
    .then((data)=>{
        res.send({
            mes: true,
            status: 200,
            data
        })
    })
    .catch((err)=>{
        console.log(err)
    })
})
//查询
router.get('/search',(req, res)=>{
    let {data} = req.query
    const sql =`select * from blogpost where title='${data}' or classify='${data}'`
    execSQL(sql)
    .then((data)=>{
        res.send({
            mes: true,
            status: 200,
            data
        })
        console.log('查询成功')
    })
    .catch((err)=>{
        res.send({
            mes: false,
            status: 200
        })
        console.log('查询失败')
    })
})
//上传markdow
router.post('/psmd',(req,res)=>{
    let {mddata,username,createtime,titex}=req.body    
    console.log(`姓名：'${username}',分类：'${titex.psify}',时间：'${createtime}',标题：'${titex.title}',简介：'${titex.describe}'`)
    const sql=`insert into blogpost(author,content,classify,createtime,title,brief)values('${username}','${mddata}','${titex.psify}','${createtime}','${titex.title}','${titex.describe}');`
    execSQL(sql)
    .then((data)=>{
        res.send({
            mes: true,
            status: 200,
        })
        console.log('写入成功')
    })
    .catch((err)=>{
        res.send({
            mes: false,
            status: 200,
            err
        })
        console.log('写入失败:',err)
    })
})
//图片上传
router.post('/image',(req,res)=>{
    console.log('触发img事件')
    var form = new formidable.IncomingForm()
    // form.encoding = 'utf-8' 
    form.uploadDir =path.join(__dirname, "\../../public/img")
    form.keepExtensions = true
    form.maxFieldsSize = 4*1024*1024
    form.parse(req,function(err, fields, fildes){
        let img_path=`http://localhost:3000/static/img/${path.basename(fildes.file.path)}`     
        if(err) {
            console.log('图片失败',err)
            res.send({
                mes:false
            })
            return;
        }
        res.send({
            fields,
            fildes,
            img_path,
            mes: true
        })
        console.log('图片成功')
    })
})
router.get('/del',(req,res)=>{
    let {id}=req.query
    // console.log(id)
    const sql = `delete from blogpost where id='${id}'`
    execSQL(sql)
    .then((data)=>{
        res.send({
            mes:true,
            status: 200
        })
    })
    .catch((err)=>{
        console.log('删除错误',err)
        res.send({
            mes:false,
            status:200,
            err
        })
    })
})
router.get('/user',(req,res)=>{
    const sql=`select id,username,weight from blogs;`
    execSQL(sql)
    .then((data)=>{
        res.send({
            mes:true,
            status: 200,
            data
        })
    })
    .catch((err)=>{
        console.log(err)
    })
})
router.get('/deluser',(req,res)=>{
    let {id}=req.query
    const sql=`delete from blogs where id='${id}'`
    console.log(sql)
    execSQL(sql)
    .then((data)=>{
        res.send({
            mes: true,
            status: 200
        })
    })
    .catch((err)=>{
        console.log(err)
    })
})
module.exports = router